package mqtt

import io.circe.ParsingFailure
import io.circe.parser.parse
import mqtt.EdgeDomain.Credential
import pdi.jwt.{JwtAlgorithm, JwtUtils}

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.SimpleTimeZone
import scala.io.Source

object MqttUtils {

  def formattingTimestamp(pattern: String, timestamp: Timestamp): String = {
    val formatter = new SimpleDateFormat(pattern)
    formatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"))
    formatter.format(timestamp)
  }

  def getEventTimestamp(timestamp: Timestamp): String =
    formattingTimestamp("yyyyMMdd'T'HHmmss'Z'", timestamp)

  def getAuthTimestamp(timestamp: Timestamp): String =
    formattingTimestamp("yyyyMMddHH", timestamp)

  def HmacSHA256Encryption(secret: String, timestamp: Timestamp): String = {
    JwtUtils.sign(
      data = secret,
      key = getAuthTimestamp(timestamp),
      algorithm = JwtAlgorithm.HS256
    ).map("%02X" format (_: Byte)).mkString.toLowerCase
  }

  def readCredentials(deviceType: String): List[Credential] = {
    //noinspection SourceNotClosed
    val lines: String = Source
      .fromFile(s"src/main/resources/json/${deviceType.toUpperCase}-DEVICES-KEY.json")
      .getLines
      .mkString

    parse(lines) match {
      case Left(parsingFailure: ParsingFailure) =>
        println(s"Json parsing error: ${parsingFailure.message}")
        throw parsingFailure.underlying
      case Right(jsonValue) =>
        jsonValue.as[List[Credential]].getOrElse(List.empty[Credential])
    }
  }

}
